package com.anycl.customer.servlet.customer;

import com.anycl.customer.entity.Customer;
import com.anycl.customer.exception.CustomerException;
import com.anycl.customer.service.CustomerService;
import com.anycl.customer.service.impl.CustomerServiceImpl;
import com.anycl.customer.vo.CustomerVo;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/customer/add")
public class CustomerAddServlet extends HttpServlet {

    private CustomerService customerService;

    @Override
    public void init() throws ServletException {
        customerService = new CustomerServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CustomerVo customerVo = buildCustomerVo(req);
        try {
            CustomerVo response = customerService.addCustomer(customerVo, req.getSession());
            resp.getWriter().write("客户信息添加成功，客户id：" + response.getId() + "，客户名字：" + response.getName());
        } catch (CustomerException e) {
            resp.getWriter().write("error: " + e.getMessage());
        }
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        if (method.equalsIgnoreCase("get")) {
            doGet(req, resp);
        } else {
            doPost(req, resp);
        }
    }

    private CustomerVo buildCustomerVo(HttpServletRequest req) {
        String name = req.getParameter("name");
        String address = req.getParameter("address");
        String telephone = req.getParameter("telephone");
        String email = req.getParameter("email");
        String remark = req.getParameter("remark");
        if (remark == null)
            remark = "";
        return CustomerVo.builder().name(name)
                .address(address)
                .telephone(telephone)
                .email(email)
                .remark(remark).build();
    }
}
